// File Name: adc_ctrl.c
// Author: kukukukuku~
// Date: 2024-06-26

#include "./User/ADC/inc/adc_ctrl.h"

uint16_t adcData[ADC_CH_NUM];   //ADC数据

double temperature; //温度值
double vRef;        //参考电压值

/**
 * @brief   ADC初始化
 * @param   None
 * @retval  None
 * @note    静态函数
*/
static void adc_init(void)
{
//    gpio_init_type gpioInitStruct = 
//    {
//        .gpio_pins           = ADC_DRIVER_GPIO_PIN,
//        .gpio_out_type       = GPIO_OUTPUT_PUSH_PULL,
//        .gpio_pull           = GPIO_PULL_NONE,
//        .gpio_mode           = GPIO_MODE_ANALOG,
//        .gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER,
//    };
    
    dma_init_type dmaInitStruct = 
    {
        .buffer_size           = ADC_CH_NUM,
        .direction             = DMA_DIR_PERIPHERAL_TO_MEMORY,
        .memory_base_addr      = (uint32_t)adcData,
        .memory_data_width     = DMA_MEMORY_DATA_WIDTH_HALFWORD,
        .memory_inc_enable     = TRUE,
        .peripheral_base_addr  = (uint32_t)&(ADC1->odt),
        .peripheral_data_width = DMA_PERIPHERAL_DATA_WIDTH_HALFWORD,
        .peripheral_inc_enable = FALSE,
        .priority              = DMA_PRIORITY_HIGH,
        .loop_mode_enable      = TRUE,
    };
    
    adc_base_config_type adcBaseInitStruct = 
    {
        .sequence_mode           = TRUE,
        .repeat_mode             = TRUE,
        .data_align              = ADC_RIGHT_ALIGNMENT,
        .ordinary_channel_length = ADC_CH_NUM,
    };
    
    //ADC GPIO初始化
//    crm_periph_clock_enable(ADC_DRIVER_GPIO_CRM, TRUE);
//    gpio_init(ADC_DRIVER_GPIO_PORT, &gpioInitStruct);
    
    //ADC DMA初始化
    crm_periph_clock_enable(ADC_DMA_CRM, TRUE);
    dma_reset(ADC_DMA_CH);
    dma_init(ADC_DMA_CH, &dmaInitStruct);
    dma_flag_clear(ADC_DMA_FDT_FLAG);
    dma_interrupt_enable(ADC_DMA_CH, DMA_FDT_INT, TRUE);
    dma_channel_enable(ADC_DMA_CH, TRUE);
    
    //ADC ADC初始化
    crm_periph_clock_enable(ADC_CRM, TRUE);
    crm_adc_clock_div_set(CRM_ADC_DIV_6);
    adc_base_config(ADC1, &adcBaseInitStruct);
    adc_ordinary_channel_set(ADC1, ADC_CH_TEMPERATURE, ADC_SEQUENCE_TEMPERATURE, ADC_SAMPLETIME_239_5);
    adc_ordinary_channel_set(ADC1, ADC_CH_VREF, ADC_SEQUENCE_VREF, ADC_SAMPLETIME_239_5);
    adc_ordinary_conversion_trigger_set(ADC1, ADC12_ORDINARY_TRIG_SOFTWARE, TRUE);
    adc_tempersensor_vintrv_enable(TRUE);
    adc_dma_mode_enable(ADC1, TRUE);
    
    adc_enable(ADC1, TRUE);
    adc_calibration_init(ADC1);
    while(adc_calibration_init_status_get(ADC1));
    adc_calibration_start(ADC1);
    while(adc_calibration_status_get(ADC1));
    
    //ADC NVIC初始化
    nvic_irq_enable(ADC_DMA_IRQ, 0, 0);
}


/**
 * @brief   ADC配置
 * @param   None
 * @retval  None
 * @note    None
*/
void adc_config(void)
{
    adc_init();
}
